import React, {createRef, useEffect, useLayoutEffect, useState} from 'react';
import cla from 'classnames';

import styles from './index.module.scss';


interface Props {
  children?: React.ReactNode;
  expanded: boolean;
  className?: string;
}

export function ToggleAnimate(props: Props) {
  const ref = createRef<HTMLDivElement>();
  const [isInit, setIsInit] = useState(false);
  const contentRef = createRef<HTMLDivElement>();
  const [height, setHeight] = useState(0);


  useEffect(() => {
    setIsInit(true);
    if (props.expanded) {
      ref.current!.style.display = 'none';
      setHeight(0);
    } else {
      ref.current!.style.display = 'block';
      setHeight(contentRef.current!.scrollHeight);
    }
  }, []);



  useLayoutEffect(() => {
    if (!ref.current || !isInit) return;

    if (props.expanded) {
      if (ref.current.style.display === 'block') {
        setHeight(0);
      }
    } else {
      ref.current.style.display = 'block';
      setHeight(0);

      requestAnimationFrame(() => {
        setHeight(contentRef.current!.scrollHeight);
      })
    }

  }, [props.expanded, isInit])


  return (
    <div style={{ height: height + 'px' }}  ref={ref} className={cla(props.className, styles['toggle-animate-wrap'])}>
      <div ref={contentRef}>{props.children }</div>
    </div>
  );
}